package jdbc.utils;

import org.junit.Test;

import java.io.Reader;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

//该类演示如何使用JDBCUtils工具类，完成dml 和 select
public class JDBCUtils_Use {
    //查询操作
    public static void main(String[] args) {
        //1. 得到连接
        Connection connection = null;
        //2. 组织一个sql
        String sql = "select * from customer";
        //3. 创建PreparedStatement 对象
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            connection = JDBCUtils.getConnection();
            preparedStatement = connection.prepareStatement(sql);
            //执行, 得到结果集
            resultSet = preparedStatement.executeQuery();
            //遍历该结果集
            while (resultSet.next()){
                int customer_id = resultSet.getInt("customer_id");
                String name = resultSet.getString("name");
                String address = resultSet.getString("address");
                String email = resultSet.getString("email");
                String sex = resultSet.getString("sex");
                int card_id = resultSet.getInt("card_id");
                System.out.println(customer_id + "\t" + name + "\t" + address
                        + "\t" + email + "\t" + sex + "\t" + card_id);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            //关闭资源
            JDBCUtils.closConnection(resultSet,connection,preparedStatement);
        }
    }

    //insert , update, delete操作
    @Test
    public void testDML(){
        //1. 得到连接
        Connection connection = null;
        //2. 组织一个sql
        String sql = "update admin set pwd = ? where NAME = ?";
        //3. 创建PreparedStatement 对象
        PreparedStatement preparedStatement = null;
        try {
            connection = JDBCUtils.getConnection();
            preparedStatement = connection.prepareStatement(sql);
            //给占位符赋值
            preparedStatement.setString(1,"000000");
            preparedStatement.setString(2,"tom");
            //执行
            preparedStatement.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            //关闭资源
            JDBCUtils.closConnection(null,connection,preparedStatement);
        }
    }
}
